<template>
  <el-scrollbar>
    <div class="p-5">
      <el-collapse accordion>
        <el-collapse-item
          v-for="(group, groupIndex) in groups"
          :title="group.title"
          :data-index="groupIndex"
          @mouseover="handleMouseover($event, groupIndex)"
        >
          <el-descriptions :column="1" border>
            <el-descriptions-item v-for="(item, itemIndex) in group.items" :label="item.title">
              <el-button
                size="small"
                type="primary"
                plain
                :data-index="itemIndex"
                @click="handleSend(item)"
                >发送</el-button
              >
            </el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
      </el-collapse>
    </div>
  </el-scrollbar>
  <el-popover
    placement="left"
    ref="popoverRef"
    :virtual-ref="itemRef"
    trigger="hover"
    virtual-triggering
  >
    <span> {{ popoverContent }} </span>
  </el-popover>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useMessageEditorStore } from '@/manager/store'
import type { ICommonPhrasesGroup, ICommonPhrasesItem } from '@/manager/types'

const itemRef = ref()
const popoverRef = ref()

const groups = reactive<ICommonPhrasesGroup[]>([
  {
    title: '组1',
    items: [
      {
        title: '组1-1标题',
        content: '组1-1内容'
      },
      {
        title: '组1-2标题',
        content: '组1-2内容'
      },
      {
        title: '组1-3标题',
        content: '组1-3内容'
      }
    ]
  },
  {
    title: '组2',
    items: [
      {
        title: '组2-1标题',
        content: '组2-1内容'
      },
      {
        title: '组2-2标题',
        content: '组2-2内容'
      },
      {
        title: '组2-3标题',
        content: '组2-3内容'
      }
    ]
  }
])

const popoverContent = ref('')

const handleMouseover = (e: Event, groupIndex: number) => {
  const target = e.target as Element
  if (target.closest('.el-descriptions__cell')) {
    const tr = target.closest('tr')
    const btn = tr?.querySelector('.el-button') as HTMLElement
    const itemIndex = parseInt(btn.dataset.index as string)
    itemRef.value = tr
    popoverContent.value = groups[groupIndex].items[itemIndex].content
  }
}

const messageEditorStore = useMessageEditorStore()
const handleSend = (item: ICommonPhrasesItem) => {
  messageEditorStore.replaceContent(item.content)
}
</script>

<style scoped>
:deep(.el-descriptions__content) {
  width: 70px;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 15px;
}

:deep(.el-descriptions__cell) {
  padding-bottom: 0;
}
</style>
